//Date: 2023-11-03 20:02:10
//LastEditors: jie zhengjie_liang@qq.com
//LastEditTime: 2023-11-26 00:19:54
//FilePath: /photowall/main/options/database_opts.go

package options

import (
	"fmt"
	"photowall/pkg/config"
	"photowall/pkg/log"
	"sync"

	"github.com/jmoiron/sqlx"
)

var (
	mainSqlConnSyncOnce sync.Once
	maintSqlConn        *sqlx.DB
)

//description: 返回通用的sql数据库连接
//return {*}

func GetMainSqlConn() *sqlx.DB {
	mainSqlConnSyncOnce.Do(func() {
		//用户名:密码 @tcp(ip:端口)/数据库的名字
		dsn := config.GetConfig().ServiceConfig.DatabaseConfig.DatabaseUserName + ":" +
			config.GetConfig().ServiceConfig.DatabaseConfig.DatabasePassword +
			"@tcp(" + config.GetConfig().ServiceConfig.DatabaseConfig.MariadbAddr +
			")/" + config.GetConfig().ServiceConfig.DatabaseConfig.DatabaseName +
			"?charset=" + config.GetConfig().ServiceConfig.DatabaseConfig.DatabaseCharset

		// 连接数据集
		db, err := sqlx.Connect("mysql", dsn)
		if err != nil {
			log.GetDatabaseLogger().Error(fmt.Sprintf("connect DB failed, err:%v\n", err.Error()))
			panic(err)
		}
		db.SetMaxOpenConns(10)
		db.SetMaxIdleConns(10)

		maintSqlConn = db
	})

	return maintSqlConn
}
